import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import IconsResolver from 'unplugin-icons/resolver'
import Icons from 'unplugin-icons/vite'
import tailwindcss from '@tailwindcss/vite'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 根据当前工作环境加载对应的环境变量
  const env = loadEnv(mode, '.')
  console.log('当前请求地址' + env.VITE_APP_API_URL)

  return {
    plugins: [
      vue(),
      vueDevTools(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
        imports: ['vue', 'vue-router', 'pinia'],
        // 生成自动导入的类型声明文件
        dts: './types/auto-import.d.ts',
        // 自动导入目录下的模块
        dirs: ['src/stores', 'src/utils'],
        // 配置 eslint
        eslintrc: {
          enabled: true, // 是否启用 eslint 配置
          filepath: './.eslintrc-auto-import.json', // 生成的文件位置
          globalsPropValue: true, // 全局属性值
        },
      }),
      Components({
        resolvers: [
          ElementPlusResolver({ importStyle: 'sass' }),
          IconsResolver({
            prefix: '',
            customCollections: [],
          }),
        ],
        // 生成组件的类型声明文件
        dts: './types/components.d.ts',
      }),
      Icons({
        autoInstall: false, // 自动下载使用的图标
      }),
      tailwindcss(),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/index.scss" as *;`,
        },
      },
    },
    server: {
      host: '0.0.0.0',
      port: 9105,
      proxy: {
        '/api': {
          target: env.VITE_APP_API_URL || 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
        '/uploads': {
          target: env.VITE_APP_API_URL || 'http://localhost:8080',
          changeOrigin: true,
        },
        '/ws': {
          target: env.VITE_APP_API_URL || 'http://localhost:9083',
          changeOrigin: true,
          ws: true,
        },
      },
    },
  }
})
